package com.lagou.seckill.mvc.service;

import com.lagou.seckill.constant.Constants;
import com.lagou.seckill.constant.StatusEnum;
import com.lagou.seckill.dto.Response;
import com.lagou.seckill.util.OrderUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Slf4j
@Service
@RequiredArgsConstructor
public final class OrderService {

    final RocketMQTemplate rocketMQTemplate;

    final RedisTemplate redisTemplate;

    public Response order(String commodityId) {
        String order = OrderUtil.generateOrder(commodityId);
        Assert.isTrue(redisTemplate.opsForValue().setIfAbsent(order, StatusEnum.INIT.code), "请勿重复下单!");
        Long stock = redisTemplate.opsForValue().decrement(Constants.STOCK_PREFIX + commodityId, 1);
        if (stock < 0) {
            redisTemplate.delete(order);
            throw new IllegalStateException("库存不足");
        }
        log.info("发送下单消息:{}", commodityId);
        rocketMQTemplate.convertAndSend(Constants.ORDER_TOPIC, order);
        log.info("发送超时消息:{}", commodityId);
        rocketMQTemplate.syncSend(Constants.DELAY_TOPIC, MessageBuilder.withPayload(order).build(), 3000, 3);
        log.info("发送超时消息成功:{}", commodityId);
        return Response.OK();
    }
}
